const post = require('../dataBase/post');
const createPost = async (req, res) => {
  try {
    // 参数校验
    if (!req.body.title?.trim()) {
      return res.status(400).json({ error: 'title 不能为空' });
    }
    if (!req.body.content || typeof req.body.content !== 'object') {
      return res.status(400).json({ error: 'content 必须是 JSON 对象' });
    }
    // 创建帖子
    const newPost = await post.create({
      title: req.body.title,
      content: req.body.content,
      author_id: req.auth.user_id,
      status: req.body.status // 可选参数（如：draft/published）
    });

    res.status(201).json(newPost);
  } catch (err) {
    const statusCode = err.message.includes('JSON') ? 400 : 500;
    res.status(statusCode).json({ error: err.message });
  }
};

const getPost = async (req, res) => {
  try {
    const posts = await post.getById(req.params.id);
    if (!posts) return res.status(404).json({ error: 'Post not found' });

    // 记录浏览量
    await post.incrementViews(req.params.id);

    res.json(posts);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

const getPostAll = async (req, res) => {
  try {
    const posts = await post.getAll();
    if (!posts) return res.status(404).json({ error: 'Post not found' });

    res.json(posts);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

const getPostPaginated = async (req, res) => {
  try {
    const { cursor, page_size = 10, my_posts = false } = req.query
    const pageSize = Math.min(parseInt(page_size), 100)

    if (my_posts) {
      const userId = req.auth.user_id
      const result = await post.getPaginated(cursor, pageSize, userId)
      res.json({
        code: 200,
        data: result
      })
    }
    else {
      const result = await post.getPaginated(cursor, pageSize)
      res.json({
        code: 200,
        data: result
      })
    }

  } catch (error) {
    console.error('分页查询失败:', error)
    res.status(500).json({
      code: 500,
      message: '分页查询失败'
    })
  }
};
const updatePost = async (req, res) => {
  try {
    // 验证作者身份
    const existingPost = await post.getById(req.params.id);
    if (!existingPost) return res.status(404).json({ error: 'Post not found' });
    if (existingPost.author_id !== req.auth.user_id) {
      return res.status(403).json({ error: 'Unauthorized' });
    }

    // 构建更新数据
    const updateData = {};
    if (req.body.title) {
      if (typeof req.body.title !== 'string') {
        return res.status(400).json({ error: 'title 必须是字符串' });
      }
      updateData.title = req.body.title;
    }

    if (req.body.content) {
      // 校验 content 是否为合法 JSON
      try {
        JSON.parse(JSON.stringify(req.body.content));
      } catch (err) {
        return res.status(400).json({ error: 'content 必须是有效的 JSON 格式' });
      }
      updateData.content = JSON.stringify(req.body.content);
    }

    // 添加更新时间戳
    updateData.updated_at = new Date();

    const updatedPost = await post.update(req.params.id, updateData);
    res.json(updatedPost);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

const deletePost = async (req, res) => {
  try {
    // 验证作者身份
    const existingPost = await post.getById(req.params.id);
    if (!existingPost) return res.status(404).json({ error: 'Post not found' });
    if (existingPost.author_id !== req.auth.user_id) {
      return res.status(403).json({ error: 'Unauthorized' });
    }

    await post.delete(req.params.id);
    res.json({ message: 'Post deleted' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
module.exports = { createPost, getPost, getPostAll, getPostPaginated, updatePost, deletePost };